package com.smh.aiagent.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shiminghui
 * @date 2025/6/4 20:09
 * @description: 一个网页搜索工具
 */
public class WebSearchTool {

    // SearchAPI 的搜索接口地址
    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    private final String apiKey;

    public WebSearchTool(String apiKey) {
        this.apiKey = apiKey;
    }

    @Tool(description = "Search for information from Bing Search Engine")
    public String searchWeb(@ToolParam(description = "Search query keyword") String query,
                            ToolContext toolContext) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("api_key", apiKey);
        paramMap.put("engine", "bing");
        try {
            String response = HttpUtil.get(SEARCH_API_URL, paramMap);
            // 增加延迟确保数据加载完整（实际优先建议通过接口参数控制返回节奏）
            Thread.sleep(1000);

            JSONObject jsonObject = JSONUtil.parseObj(response);

            // 判断是否存在 organic_results 字段
            if (!jsonObject.containsKey("organic_results")) {
                return "No results found in the response.";
            }

            JSONArray organicResults = jsonObject.getJSONArray("organic_results");

            // 防止结果不足5条时的越界异常
            int endIndex = Math.min(5, organicResults.size());
            List<Object> objects = organicResults.subList(0, endIndex);

            String result = objects.stream().map(obj -> {
                JSONObject tmpJSONObject = (JSONObject) obj;
                HashMap<String, String> map = new HashMap<>();
                map.put("title", tmpJSONObject.getStr("title"));
                map.put("link", tmpJSONObject.getStr("link"));
                map.put("snippet", tmpJSONObject.getStr("snippet"));
                return JSONUtil.toJsonStr(map);
            }).collect(Collectors.joining(","));

            return result;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
            return "Request was interrupted: " + e.getMessage();
        } catch (Exception e) {
            return "Error searching Baidu: " + e.getMessage();
        }
    }
}

